/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tuoc;

import java.sql.*;
import java.util.Vector;
import javax.sql.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

/**
 *
 * @author apple
 */
public class My_model {
    
    Connection conn;
    Statement st;
    String databaseName;
    String port;
    String userName;
    String password;
    
    public My_model()
    {
        readConfig();
    }
    
    public void get_connection()
    {
        this.readConfig();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:"+port+"/"+databaseName,userName,password);
        } catch (Exception e) {
            e.printStackTrace();;
        }
    }
    
    public void close_connection()
    {
        try {
            conn.close();
            st.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public int insertDatabase(String sql)
    {
        int inserted_id = -1;
        try {
            this.get_connection();
            st = conn.createStatement();
            inserted_id = st.executeUpdate(sql,st.RETURN_GENERATED_KEYS);
            ResultSet keys = st.getGeneratedKeys();  
            keys.next();  
            inserted_id = keys.getInt(1);  
            keys.close(); 
            this.close_connection();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inserted_id;
        
    }
    
    public ResultSet executeSqlString(String sql)
    {
        ResultSet rs = null;
        try {
            this.get_connection();
            st = conn.createStatement();
            rs = st.executeQuery(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        

        return rs;
    }
    
    public void readConfig()
    {
        try {
 
	File fXmlFile = new File("config.xml");
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(fXmlFile);
 
	NodeList nl = doc.getElementsByTagName("database");
        Node n = nl.item(0);   
        databaseName = n.getTextContent();
        
        
        nl = doc.getElementsByTagName("port");
        n = nl.item(0);   
        port = n.getTextContent();
        
        nl = doc.getElementsByTagName("username");
        n = nl.item(0);   
        userName = n.getTextContent();
        
        nl = doc.getElementsByTagName("password");
        n = nl.item(0);   
        password = n.getTextContent();
        
    } catch (Exception e) {
	e.printStackTrace();
    }
    }
    
}
